/*
 * Copyright (c) 2009.
 */

package kz.home;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

/**
 * <strong>title</strong>
 * <p> describe
 *
 * @author: Danik <br>
 * Date: 14.07.2009  <br>
 * Time: 17:23:12  <br>
 */
public class TestStore2 extends MIDlet {
    String DB = "DB";
    
    protected void startApp() throws MIDletStateChangeException {
        dropDB();
        createDB();
        writeToDB();
        readFromDB();
    }

    private void dropDB() {
        try {
            RecordStore.deleteRecordStore(DB);
            System.out.println(" has been deleted ");
        } catch (RecordStoreException e) {
            e.printStackTrace();
        }
    }

    private void readFromDB() {
        try {
            RecordStore store = RecordStore.openRecordStore(DB, false);
            System.out.println("num [" + store.getNumRecords() + "]");

            for (int i = 1; i <= store.getNumRecords(); i++) {
                byte[] data = store.getRecord(i);
                DataInputStream is = new DataInputStream(new ByteArrayInputStream(data));
                //is.
                System.out.println("[" + is.readUTF() + "]");
                System.out.println("");
            }
            store.closeRecordStore();
            System.out.println(" has been read ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void writeToDB() {
        try {
            RecordStore rs = RecordStore.openRecordStore(DB, false);
            ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
            DataOutputStream data = new DataOutputStream(byteOutput);
            data.writeUTF("один");
            data.writeUTF("два");
            data.writeUTF("три");
            //
            rs.addRecord(byteOutput.toByteArray(), 0, byteOutput.size());
            //
            rs.closeRecordStore();
            System.out.println(" has been written ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createDB() {
        try {
            RecordStore rs = RecordStore.openRecordStore(DB, true);
            System.out.println(" has been created");
            rs.closeRecordStore();
        } catch (RecordStoreException e) {
            e.printStackTrace();
        }
    }

    protected void pauseApp() {

    }

    protected void destroyApp(boolean b) throws MIDletStateChangeException {

    }
}
